# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
# https://github.com/xxks-kkk/shuati/blob/master/leetcode/236-LowestCommonAncestorOfABinaryTree/lowestCommonAncestorOfABinaryTree.py
class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        if not root or root==p or root == q :
            return root
        left  = self.lowestCommonAncestor(root.left, p, q)
        right  = self.lowestCommonAncestor(root.right, p, q)
        if left and right:
            return root
        else :
            return left or right
        
